<template>
  <div class="notice-management">
    <!-- 顶部操作栏 -->
    <div class="header-actions">
      <el-card class="action-card">
        <div class="action-bar">
          <div class="left-actions">
            <!-- 发布公告按钮 - 只对管理员显示 -->
            <el-button type="primary" @click="handleAdd" v-if="isAdmin">
              <el-icon><Plus /></el-icon>
              发布公告
            </el-button>
            <!-- 批量删除按钮 - 只对管理员显示 -->
            <el-button 
              type="danger" 
              :disabled="selectedNotices.length === 0"
              @click="handleBatchDelete"
              v-if="isAdmin"
            >
              <el-icon><Delete /></el-icon>
              批量删除
            </el-button>
          </div>
          <div class="right-actions">
            <el-input
              v-model="searchForm.keyword"
              placeholder="请输入公告标题或内容"
              clearable
              style="width: 300px"
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            <el-select
              v-model="searchForm.status"
              placeholder="状态"
              clearable
              style="width: 120px; margin-left: 10px"
              @change="handleSearch"
            >
              <el-option label="已发布" value="1" />
              <el-option label="草稿" value="0" />
            </el-select>
            <el-button type="primary" @click="handleSearch" style="margin-left: 10px">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 统计信息 -->
    <div class="statistics-panel">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-item">
              <div class="stat-icon published">
                <el-icon><Bell /></el-icon>
              </div>
              <div class="stat-content">
                <div class="stat-value">{{ statistics.publishedCount }}</div>
                <div class="stat-label">已发布公告</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-item">
              <div class="stat-icon draft">
                <el-icon><Document /></el-icon>
              </div>
              <div class="stat-content">
                <div class="stat-value">{{ statistics.draftCount }}</div>
                <div class="stat-label">草稿公告</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-item">
              <div class="stat-icon topped">
                <el-icon><Star /></el-icon>
              </div>
              <div class="stat-content">
                <div class="stat-value">{{ statistics.toppedCount }}</div>
                <div class="stat-label">置顶公告</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-item">
              <div class="stat-icon total">
                <el-icon><DataAnalysis /></el-icon>
              </div>
              <div class="stat-content">
                <div class="stat-value">{{ statistics.totalCount }}</div>
                <div class="stat-label">总公告数</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 公告列表 -->
    <div class="notice-list">
      <el-card class="table-card">
        <el-table
          v-loading="loading"
          :data="noticeList"
          style="width: 100%"
          stripe
          border
          empty-text="暂无公告数据"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="title" label="标题" min-width="200" show-overflow-tooltip>
            <template #default="{ row }">
              <div class="notice-title-cell">
                <el-icon v-if="row.isTop" class="top-icon">
                  <Star />
                </el-icon>
                <span class="notice-title">{{ row.title }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="content" label="内容预览" min-width="300" show-overflow-tooltip>
            <template #default="{ row }">
              <span class="content-preview">{{ getContentPreview(row.content) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="publishStatus" label="状态" width="100" align="center">
            <template #default="{ row }">
              <el-tag :type="getStatusTagType(row.publishStatus)">
                {{ getStatusText(row.publishStatus) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="publishTime" label="发布时间" width="160" align="center">
            <template #default="{ row }">
              {{ formatDateTime(row.publishTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="160" align="center">
            <template #default="{ row }">
              {{ formatDateTime(row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="publisherName" label="创建人" width="100" align="center" />
          <el-table-column label="操作" width="280" fixed="right" align="center">
            <template #default="{ row }">
              <el-button
                type="primary"
                link
                @click="handleView(row)"
              >
                <el-icon><View /></el-icon>
                查看
              </el-button>
              <!-- 编辑按钮 - 只对管理员显示 -->
              <el-button
                type="primary"
                link
                @click="handleEdit(row)"
                v-if="isAdmin"
              >
                <el-icon><Edit /></el-icon>
                编辑
              </el-button>
              <!-- 发布按钮 - 只对管理员显示 -->
              <el-button
                v-if="row.publishStatus === 0 && isAdmin"
                type="success"
                link
                @click="handlePublish(row)"
              >
                <el-icon><Position /></el-icon>
                发布
              </el-button>
              <!-- 撤回按钮 - 只对管理员显示 -->
              <el-button
                v-if="row.publishStatus === 1 && isAdmin"
                type="warning"
                link
                @click="handleUnpublish(row)"
              >
                <el-icon><Remove /></el-icon>
                撤回
              </el-button>
              <!-- 置顶按钮 - 只对管理员显示 -->
              <el-button
                v-if="!row.isTop && isAdmin"
                type="warning"
                link
                @click="handleTop(row)"
              >
                <el-icon><Star /></el-icon>
                置顶
              </el-button>
              <!-- 取消置顶按钮 - 只对管理员显示 -->
              <el-button
                v-if="row.isTop && isAdmin"
                type="info"
                link
                @click="handleUntop(row)"
              >
                <el-icon><StarFilled /></el-icon>
                取消置顶
              </el-button>
              <!-- 删除按钮 - 只对管理员显示 -->
              <el-button
                type="danger"
                link
                @click="handleDelete(row)"
                v-if="isAdmin"
              >
                <el-icon><Delete /></el-icon>
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-wrapper">
          <el-pagination
            :current-page="pagination.page"
            :page-size="pagination.size"
            :total="pagination.total"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>

    <!-- 新增/编辑公告对话框 -->
    <el-dialog
      v-model="editDialog.visible"
      :title="editDialog.isEdit ? '编辑公告' : '发布公告'"
      width="70%"
      :before-close="handleCloseEdit"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editRules"
        label-width="80px"
        class="edit-form"
      >
        <el-form-item label="公告标题" prop="title">
          <el-input
            v-model="editForm.title"
            placeholder="请输入公告标题"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="公告内容" prop="content">
          <el-input
            v-model="editForm.content"
            type="textarea"
            :rows="10"
            placeholder="请输入公告内容"
            maxlength="2000"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="是否置顶">
          <el-switch
            v-model="editForm.isTop"
            active-text="置顶"
            inactive-text="不置顶"
          />
        </el-form-item>
        
        <el-form-item label="发布状态">
          <el-radio-group v-model="editForm.status">
            <el-radio :value="0">保存为草稿</el-radio>
            <el-radio :value="1">立即发布</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCloseEdit">取消</el-button>
          <el-button type="primary" @click="handleSaveNotice" :loading="editDialog.loading">
            {{ editDialog.isEdit ? '更新' : '发布' }}
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 查看公告对话框 -->
    <el-dialog
      v-model="viewDialog.visible"
      title="查看公告"
      width="60%"
    >
      <div v-if="viewDialog.data" class="notice-view">
        <div class="notice-header">
          <h2 class="notice-title">{{ viewDialog.data.title }}</h2>
          <div class="notice-meta">
            <el-tag :type="getStatusTagType(viewDialog.data.publishStatus)">
              {{ getStatusText(viewDialog.data.publishStatus) }}
            </el-tag>
            <el-tag v-if="viewDialog.data.isTop" type="warning" style="margin-left: 10px">
              <el-icon><Star /></el-icon>
              置顶
            </el-tag>
          </div>
        </div>
        
        <div class="notice-info">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="创建人">{{ viewDialog.data.publisherName }}</el-descriptions-item>
            <el-descriptions-item label="创建时间">{{ formatDateTime(viewDialog.data.createTime) }}</el-descriptions-item>
            <el-descriptions-item label="发布时间">{{ formatDateTime(viewDialog.data.publishTime) }}</el-descriptions-item>
            <el-descriptions-item label="更新时间">{{ formatDateTime(viewDialog.data.updateTime) }}</el-descriptions-item>
          </el-descriptions>
        </div>
        
        <div class="notice-content">
          <h4>公告内容</h4>
          <div class="content-text">{{ viewDialog.data.content }}</div>
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="viewDialog.visible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  Search,
  Delete,
  Edit,
  View,
  Position,
  Remove,
  Star,
  StarFilled,
  Bell,
  Document,
  DataAnalysis
} from '@element-plus/icons-vue'
import {
  getAdminNoticeList,
  createNotice,
  saveDraft,
  updateNotice,
  deleteNotice,
  getNoticeDetail,
  withdrawNotice,
  setTopNotice,
  getNoticeStatistics
} from '@/api/notice'
import { useUserStore } from '@/stores/user'
import { computed } from 'vue'

// 获取用户状态
const userStore = useUserStore()

// 判断是否为管理员
const isAdmin = computed(() => {
  // 检查用户名是否为admin，或者角色是否包含ADMIN
  return userStore.userInfo?.username === 'admin' || 
         userStore.roles.includes('ADMIN') || 
         userStore.roles.includes('admin')
})

// 搜索表单
const searchForm = reactive({
  keyword: '',
  status: ''
})

// 列表数据
const loading = ref(false)
const noticeList = ref([])
const selectedNotices = ref([])

// 统计数据
const statistics = reactive({
  publishedCount: 0,
  draftCount: 0,
  toppedCount: 0,
  totalCount: 0
})

// 分页
const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

// 编辑对话框
const editDialog = reactive({
  visible: false,
  isEdit: false,
  loading: false
})

const editFormRef = ref()
const editForm = reactive({
  id: null,
  title: '',
  content: '',
  isTop: false,
  status: 1
})

const editRules = {
  title: [
    { required: true, message: '请输入公告标题', trigger: 'blur' },
    { min: 1, max: 100, message: '标题长度在1到100个字符之间', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入公告内容', trigger: 'blur' },
    { min: 1, max: 2000, message: '内容长度在1到2000个字符之间', trigger: 'blur' }
  ]
}

// 查看对话框
const viewDialog = reactive({
  visible: false,
  data: null
})

// 搜索公告
const handleSearch = async () => {
  pagination.page = 1
  await loadNoticeList()
}

// 加载公告列表
const loadNoticeList = async () => {
  try {
    loading.value = true
    const params = {
      current: pagination.page,
      size: pagination.size,
      keyword: searchForm.keyword,
      publishStatus: searchForm.status
    }
    
    const response = await getAdminNoticeList(params)
    noticeList.value = response.data.records || []
    pagination.total = response.data.total || 0
  } catch (error) {
    console.error('加载公告列表失败:', error)
    ElMessage.error('加载公告列表失败')
  } finally {
    loading.value = false
  }
}

// 加载统计数据
const loadStatistics = async () => {
  try {
    // 这里需要实现一个获取统计数据的API
    // 目前先使用模拟数据
    const mockStats = {
      publishedCount: noticeList.value.filter(n => n.publishStatus === 1).length,
      draftCount: noticeList.value.filter(n => n.publishStatus === 0).length,
      toppedCount: noticeList.value.filter(n => n.isTop === 1).length,
      totalCount: noticeList.value.length
    }
    Object.assign(statistics, mockStats)
  } catch (error) {
    console.error('加载统计数据失败:', error)
  }
}

// 新增公告
const handleAdd = () => {
  editDialog.isEdit = false
  editDialog.visible = true
  resetEditForm()
}

// 编辑公告
const handleEdit = async (row) => {
  try {
    const response = await getNoticeDetail(row.id)
    const notice = response.data
    
    editDialog.isEdit = true
    editDialog.visible = true
    
    Object.assign(editForm, {
      id: notice.id,
      title: notice.title,
      content: notice.content,
      isTop: notice.isTop,
      status: notice.status
    })
  } catch (error) {
    console.error('获取公告详情失败:', error)
    ElMessage.error('获取公告详情失败')
  }
}

// 查看公告
const handleView = async (row) => {
  try {
    const response = await getNoticeDetail(row.id)
    viewDialog.data = response.data
    viewDialog.visible = true
  } catch (error) {
    console.error('获取公告详情失败:', error)
    ElMessage.error('获取公告详情失败')
  }
}

// 发布公告（重新发布草稿）
const handlePublish = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要发布公告"${row.title}"吗？`,
      '确认发布',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }
    )
    
    // 更新发布状态为已发布
    await updateNotice(row.id, { ...row, publishStatus: 1 })
    ElMessage.success('发布成功')
    await loadNoticeList()
    await loadStatistics()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('发布公告失败:', error)
      ElMessage.error('发布公告失败')
    }
  }
}

// 撤回公告
const handleUnpublish = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要撤回公告"${row.title}"吗？`,
      '确认撤回',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await withdrawNotice(row.id)
    ElMessage.success('撤回成功')
    await loadNoticeList()
    await loadStatistics()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('撤回公告失败:', error)
      ElMessage.error('撤回公告失败')
    }
  }
}

// 置顶公告
const handleTop = async (row) => {
  try {
    await setTopNotice(row.id, 1)
    ElMessage.success('置顶成功')
    await loadNoticeList()
    await loadStatistics()
  } catch (error) {
    console.error('置顶失败:', error)
    ElMessage.error('置顶失败')
  }
}

// 取消置顶
const handleUntop = async (row) => {
  try {
    await setTopNotice(row.id, 0)
    ElMessage.success('取消置顶成功')
    await loadNoticeList()
    await loadStatistics()
  } catch (error) {
    console.error('取消置顶失败:', error)
    ElMessage.error('取消置顶失败')
  }
}

// 删除公告
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除公告"${row.title}"吗？删除后无法恢复！`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }
    )
    
    await deleteNotice(row.id)
    ElMessage.success('删除成功')
    await loadNoticeList()
    await loadStatistics()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除公告失败:', error)
      ElMessage.error('删除公告失败')
    }
  }
}

// 批量删除
const handleBatchDelete = async () => {
  if (selectedNotices.value.length === 0) {
    ElMessage.warning('请选择要删除的公告')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedNotices.value.length} 条公告吗？删除后无法恢复！`,
      '确认批量删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }
    )
    
    // 逐个删除（因为后端没有批量删除API）
    for (const notice of selectedNotices.value) {
      await deleteNotice(notice.id)
    }
    
    ElMessage.success('批量删除成功')
    selectedNotices.value = []
    await loadNoticeList()
    await loadStatistics()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    }
  }
}

// 保存公告
const handleSaveNotice = async () => {
  try {
    await editFormRef.value?.validate()
    
    editDialog.loading = true
    
    const noticeData = {
      title: editForm.title,
      content: editForm.content,
      noticeType: 1, // 默认系统公告
      priority: 1, // 默认普通优先级
      isTop: editForm.isTop ? 1 : 0,
      publishStatus: editForm.status,
      targetUserType: 0 // 默认全部用户
    }
    
    if (editDialog.isEdit) {
      await updateNotice(editForm.id, noticeData)
      ElMessage.success('更新成功')
    } else {
      if (editForm.status === 1) {
        await createNotice(noticeData)
        ElMessage.success('发布成功')
      } else {
        await saveDraft(noticeData)
        ElMessage.success('草稿保存成功')
      }
    }
    
    editDialog.visible = false
    await loadNoticeList()
    await loadStatistics()
  } catch (error) {
    if (error !== false) {
      console.error('保存公告失败:', error)
      ElMessage.error('保存公告失败')
    }
  } finally {
    editDialog.loading = false
  }
}

// 关闭编辑对话框
const handleCloseEdit = (done) => {
  editDialog.visible = false
  resetEditForm()
  if (typeof done === 'function') {
    done()
  }
}

// 重置编辑表单
const resetEditForm = () => {
  Object.assign(editForm, {
    id: null,
    title: '',
    content: '',
    isTop: false,
    status: 1
  })
  editFormRef.value?.clearValidate()
}

// 选择改变
const handleSelectionChange = (selection) => {
  selectedNotices.value = selection
}

// 分页大小改变
const handleSizeChange = (size) => {
  pagination.size = size
  pagination.page = 1
  loadNoticeList()
}

// 当前页改变
const handleCurrentChange = (page) => {
  pagination.page = page
  loadNoticeList()
}

// 获取内容预览
const getContentPreview = (content) => {
  if (!content) return '-'
  return content.length > 50 ? content.substring(0, 50) + '...' : content
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    0: '草稿',
    1: '已发布',
    2: '已撤回'
  }
  return statusMap[status] || '未知'
}

// 获取状态标签类型
const getStatusTagType = (status) => {
  const typeMap = {
    0: 'info',
    1: 'success',
    2: 'warning'
  }
  return typeMap[status] || ''
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString('zh-CN')
}

// 组件挂载时加载数据
onMounted(async () => {
  try {
    // 先加载统计数据（使用模拟数据）
    await loadStatistics()
    // 再加载公告列表
    await loadNoticeList()
  } catch (error) {
    console.error('组件初始化失败:', error)
    ElMessage.error('页面加载失败，请刷新重试')
  }
})
</script>

<style scoped>
.notice-management {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: calc(100vh - 120px);
}

.header-actions {
  margin-bottom: 20px;
}

.action-card {
  background-color: #fff;
}

.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.left-actions,
.right-actions {
  display: flex;
  gap: 10px;
  align-items: center;
}

.statistics-panel {
  margin-bottom: 20px;
}

.stat-card {
  background-color: #fff;
  border: none;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.stat-item {
  display: flex;
  align-items: center;
  padding: 10px 0;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20px;
  font-size: 24px;
  color: #fff;
}

.stat-icon.published {
  background: linear-gradient(135deg, #67C23A, #85CE61);
}

.stat-icon.draft {
  background: linear-gradient(135deg, #909399, #A6A9AD);
}

.stat-icon.topped {
  background: linear-gradient(135deg, #E6A23C, #EEBE77);
}

.stat-icon.total {
  background: linear-gradient(135deg, #409EFF, #66B1FF);
}

.stat-content {
  flex: 1;
}

.stat-value {
  font-size: 28px;
  font-weight: 600;
  color: #303133;
  line-height: 1;
}

.stat-label {
  font-size: 14px;
  color: #909399;
  margin-top: 5px;
}

.notice-list {
  margin-bottom: 20px;
}

.table-card {
  background-color: #fff;
}

.notice-title-cell {
  display: flex;
  align-items: center;
  gap: 5px;
}

.top-icon {
  color: #E6A23C;
  font-size: 16px;
}

.notice-title {
  font-weight: 500;
}

.content-preview {
  color: #606266;
  line-height: 1.5;
}

.pagination-wrapper {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.edit-form {
  padding: 20px 0;
}

.notice-view {
  padding: 20px 0;
}

.notice-header {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #EBEEF5;
}

.notice-header .notice-title {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 10px 0;
}

.notice-meta {
  display: flex;
  align-items: center;
}

.notice-info {
  margin-bottom: 20px;
}

.notice-content h4 {
  margin-bottom: 10px;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.content-text {
  background-color: #f8f9fa;
  padding: 15px;
  border-radius: 4px;
  line-height: 1.6;
  color: #606266;
  white-space: pre-wrap;
}

:deep(.el-table) {
  font-size: 14px;
}

:deep(.el-table th) {
  background-color: #fafafa;
  color: #606266;
  font-weight: 600;
}

:deep(.el-pagination) {
  justify-content: center;
}

:deep(.el-textarea__inner) {
  font-family: inherit;
}
</style>
